package socksproxy.netty.proxy_wangZha.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

/**
 * 目标服务器
 */
public class Server1 {

	private String targetHost;
	private int targetPort;


	public Server1(String targetHost, int targetPort) {
		super();
		this.targetHost = targetHost;
		this.targetPort = targetPort;
	}

	public void run() throws Exception {
		System.err.println("Target host:" + targetHost + " targetPort:"
				+ targetPort);

		// Configure the bootstrap.
		EventLoopGroup bossGroup = new NioEventLoopGroup(1);
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup)
					.channel(NioServerSocketChannel.class)
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						public void initChannel(SocketChannel ch)
								throws Exception {
							// 注册handler
							ChannelPipeline pipeline = ch.pipeline();
							pipeline.addLast("frameDecoder",
									new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0,
											4, 0, 4));
							pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
							pipeline.addLast("decoder",
									new StringDecoder(CharsetUtil.UTF_8));
							pipeline.addLast("encoder",
									new StringEncoder(CharsetUtil.UTF_8));
							pipeline.addLast("handler", new ServerHandler1());
						}
					}).bind(targetPort).sync().channel().closeFuture().sync();
			// 监听本地的一个端口，当有客户端请求时，然后向目标服务器发送请求，获取消息，然后发送给客户端
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}

	public static void main(String[] args) throws Exception {
		System.out.println("目标服务器启动....");
		new Server1("127.0.0.1", 55667).run();
	}
}
